package com.zenithmind.exam.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.Result;
import com.zenithmind.exam.pojo.dto.ExamCreateDTO;
import com.zenithmind.exam.pojo.entity.Exam;
import com.zenithmind.exam.pojo.vo.ExamVO;
import com.zenithmind.exam.pojo.vo.QuestionVO;
import com.zenithmind.exam.service.ExamService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import java.util.List;

/**
 * 考试控制器
 * 
 * @author ZenithMind
 * @since 2024-07-01
 */
@Slf4j
@RestController
@RequestMapping("/api/exam")
@RequiredArgsConstructor
@Validated
@Tag(name = "考试管理", description = "考试的增删改查操作")
public class ExamController {

    private final ExamService examService;

    @PostMapping
    @Operation(summary = "创建考试", description = "创建新的考试")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> createExam(@Valid @RequestBody ExamCreateDTO examCreateDTO) {
        boolean result = examService.createExam(examCreateDTO);
        return Result.success(result);
    }

    @PutMapping("/{examId}")
    @Operation(summary = "更新考试", description = "更新指定的考试")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> updateExam(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Valid @RequestBody ExamCreateDTO examCreateDTO) {
        boolean result = examService.updateExam(examId, examCreateDTO);
        return Result.success(result);
    }

    @DeleteMapping("/{examId}")
    @Operation(summary = "删除考试", description = "删除指定的考试")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> deleteExam(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        boolean result = examService.deleteExam(examId);
        return Result.success(result);
    }

    @GetMapping("/{examId}")
    @Operation(summary = "获取考试详情", description = "根据ID获取考试详情")
    public Result<ExamVO> getExamById(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        ExamVO exam = examService.getExamById(examId);
        return Result.success(exam);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询考试", description = "分页查询考试列表")
    public Result<IPage<ExamVO>> getExamPage(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "考试标题") @RequestParam(required = false) String title,
            @Parameter(description = "分类ID") @RequestParam(required = false) String categoryId,
            @Parameter(description = "创建者ID") @RequestParam(required = false) String creatorId,
            @Parameter(description = "考试类型") @RequestParam(required = false) Integer type,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        
        Page<Exam> page = new Page<>(pageNum, pageSize);
        IPage<ExamVO> result = examService.getExamPage(page, title, categoryId, creatorId, type, status);
        return Result.success(result);
    }

    @PostMapping("/{examId}/publish")
    @Operation(summary = "发布考试", description = "发布指定的考试")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> publishExam(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        boolean result = examService.publishExam(examId);
        return Result.success(result);
    }

    @PostMapping("/{examId}/pause")
    @Operation(summary = "暂停考试", description = "暂停指定的考试")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> pauseExam(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        boolean result = examService.pauseExam(examId);
        return Result.success(result);
    }

    @PostMapping("/{examId}/resume")
    @Operation(summary = "恢复考试", description = "恢复指定的考试")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> resumeExam(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        boolean result = examService.resumeExam(examId);
        return Result.success(result);
    }

    @PostMapping("/{examId}/end")
    @Operation(summary = "结束考试", description = "结束指定的考试")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> endExam(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        boolean result = examService.endExam(examId);
        return Result.success(result);
    }

    @GetMapping("/{examId}/questions")
    @Operation(summary = "获取考试题目", description = "获取考试的题目列表")
    public Result<List<QuestionVO>> getExamQuestions(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Parameter(description = "是否显示答案") @RequestParam(defaultValue = "false") Boolean showAnswer) {
        String userId = UserContext.getUserId();
        List<QuestionVO> questions = examService.getExamQuestions(examId, userId, showAnswer);
        return Result.success(questions);
    }

    @PostMapping("/{examId}/start")
    @Operation(summary = "开始考试", description = "学生开始参加考试")
    @PreAuthorize("hasRole('STUDENT') or hasRole('USER')")
    public Result<String> startExam(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        String userId = UserContext.getUserId();
        String examRecordId = examService.startExam(examId, userId);
        return Result.success(examRecordId);
    }

    @GetMapping("/{examId}/can-take")
    @Operation(summary = "检查是否可以参加考试", description = "检查用户是否可以参加指定考试")
    public Result<Boolean> canUserTakeExam(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        String userId = UserContext.getUserId();
        boolean result = examService.canUserTakeExam(examId, userId);
        return Result.success(result);
    }

    @GetMapping("/ongoing")
    @Operation(summary = "获取进行中的考试", description = "获取当前进行中的考试列表")
    public Result<List<ExamVO>> getOngoingExams() {
        List<ExamVO> exams = examService.getOngoingExams();
        return Result.success(exams);
    }

    @GetMapping("/upcoming")
    @Operation(summary = "获取即将开始的考试", description = "获取即将开始的考试列表")
    public Result<List<ExamVO>> getUpcomingExams() {
        List<ExamVO> exams = examService.getUpcomingExams();
        return Result.success(exams);
    }

    @GetMapping("/hot")
    @Operation(summary = "获取热门考试", description = "获取热门考试列表")
    public Result<List<ExamVO>> getHotExams(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<ExamVO> exams = examService.getHotExams(limit);
        return Result.success(exams);
    }

    @PostMapping("/{examId}/copy")
    @Operation(summary = "复制考试", description = "复制指定的考试")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> copyExam(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId,
            @Parameter(description = "新标题") @RequestParam @NotBlank String newTitle) {
        boolean result = examService.copyExam(examId, newTitle);
        return Result.success(result);
    }

    @GetMapping("/my-created")
    @Operation(summary = "获取我创建的考试", description = "获取当前用户创建的考试列表")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<List<ExamVO>> getUserCreatedExams() {
        String creatorId = UserContext.getUserId();
        List<ExamVO> exams = examService.getUserCreatedExams(creatorId);
        return Result.success(exams);
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除考试", description = "批量删除指定的考试")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> batchDeleteExams(
            @Parameter(description = "考试ID列表") @RequestBody List<String> examIds) {
        boolean result = examService.batchDeleteExams(examIds);
        return Result.success(result);
    }

    @PostMapping("/{examId}/statistics/update")
    @Operation(summary = "更新考试统计", description = "手动更新考试统计信息")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public Result<Boolean> updateExamStatistics(
            @Parameter(description = "考试ID") @PathVariable @NotBlank String examId) {
        examService.updateExamStatistics(examId);
        return Result.success(true);
    }
}
